package com.dh.web.controller;


import com.dh.core.config.Constant;
import com.dh.core.config.UserRole;
import com.dh.core.security.EnhanceSecurityUtils;
import com.dh.core.security.RoleConstant;
import com.dh.core.util.BeanValueUtil;
import com.dh.entity.User;
import com.dh.service.UserService;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.apache.shiro.authz.annotation.RequiresUser;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@RequestMapping("/admin/user")
@Controller
public class UserController {

    @Autowired
    private UserService userService;


    /**
     * 转到列表展示页
     *
     * @param model
     * @param page
     * @param nickname
     * @return
     */
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    @RequiresUser
    public String show(Model model, @RequestParam(required = false, value = "page", defaultValue = "1") int page, String nickname) {

        Page<User> pagination =
            userService.page(new PageRequest(page - 1, 100, Sort.Direction.ASC, "id"), nickname);
        model.addAttribute("pagination", pagination);
        return "admin/user/user_list";
    }

    /**
     * 转到添加页面
     *
     * @return
     */
    @RequestMapping("/new")
    @RequiresUser
    public String editNew() {
        return "admin/user/user_create";
    }



    /**
     * 添加用户
     *
     * @param user
     * @param redirectAttributes
     * @return
     */
    @RequestMapping(value = "/create", method = RequestMethod.POST)
    @RequiresUser
    public String create(User user, RedirectAttributes redirectAttributes) {

        try {
            //校验,用户名唯一存在
            User u = userService.findByUsername(user.getUsername());
            if (null != u) {
                redirectAttributes.addFlashAttribute("message", "用户已经存在");
                return "redirect:/admin/user/new";
            }

            //党员都是普通用户,角色值为1
            user.setPasswd(new Sha256Hash(user.getPasswd()).toHex());
            user.setUserType(Constant.USER_TYPE_DY);
            user.setAccountRole(UserRole.NORMARL.getId());
            userService.create(user);
        } catch (Exception e) {
            redirectAttributes.addFlashAttribute("message", "用户已经存在");
            return "redirect:/admin/user/new";
        }
        return "redirect:/admin/user/list";
    }

    /**
     * 删除一个用户
     *
     * @param id
     * @return
     */
    @RequestMapping(value = "/delete/{id}", method = RequestMethod.POST)
    @RequiresRoles(value = {RoleConstant.ROLE_ADMIN})
    public
    @ResponseBody
    Map<String, Object> delete(@PathVariable Long id) {
        Map<String, Object> map = new HashMap<>();

        Long currentUser = EnhanceSecurityUtils.reteriveEnhanceUser().getUserId();

        User u = userService.get(id);
        if (1 == u.getAdmin()) {
            map.put("success", false);
            map.put("msg", "超级管理员不能被删除");
            return map;
        }

        if (currentUser.equals(id)) {
            map.put("success", false);
            map.put("msg", "不能删除自己");
            return map;
        }
        userService.delete(id);
        map.put("success", true);
        return map;
    }


    /**
     * 转到编辑用户页
     *
     * @param id
     * @param model
     * @return
     */
    @RequestMapping(value = "/edit/{id}", method = RequestMethod.GET)
    @RequiresUser
    public String edit(@PathVariable Long id, Model model) {
        User user = userService.get(id);
        model.addAttribute("user", user);
        return "admin/user/user_update";
    }


    /**
     * 更新用户
     *
     * @param id
     * @param user
     * @param redirectAttributes
     * @return
     */
    @RequestMapping(value = "/update/{id}", method = RequestMethod.POST)
    @RequiresRoles(value = {RoleConstant.ROLE_ADMIN})
    public String update(@PathVariable("id") long id, User user, RedirectAttributes redirectAttributes) {

        try {
            User exist = userService.get(id);

            Long currentUser = EnhanceSecurityUtils.reteriveEnhanceUser().getUserId();

            if (1 == exist.getAdmin() && !exist.getId().equals(currentUser)) {
                redirectAttributes.addFlashAttribute("message", "只有管理员自己才能修改管理员");
                return "redirect:/admin/user/edit/" + id;
            }

            //修改了密码
            if (null != user.getPasswd() && user.getPasswd().length() > 0) {
                user.setPasswd(new Sha256Hash(user.getPasswd()).toHex());
            }
            User u = userService.get(id);
            user.setUserType(u.getUserType());
            BeanValueUtil.copyProperties(user, u);
            u.setLastModifyTime(new Date());

            u.setUserType(Constant.USER_TYPE_DY);
            u.setAccountRole(UserRole.NORMARL.getId());
            userService.update(u);
        } catch (Exception e) {
            redirectAttributes.addFlashAttribute("message", "出现错误");
            return "redirect:/admin/user/edit/" + id;
        }
        return "redirect:/admin/user/list";
    }

}
